<template>
    <view class="action" @tap="show">
        <text class="cuIcon-location"></text>
        <text class="city-title" v-if="positionLoading">定位中...</text>
        <text class="city-title" v-else>{{ city.title }}</text>
    </view>
</template>

<script>
let map;
import { mapState } from 'vuex'
export default {
    props: {
    },
    data(){
        return {
            positionLoading: false
        }
    },
    computed: {
        ...mapState({
            city: state => state.GLOBALSTATUS.city
        })
    },
    created() {
        map = this.$utils.useMap(()=>{
            this.getPosition();
        });
        uni.$on('x-city', (res) => {
            this.$store.dispatch('setCity', res);
            uni.$emit('x-city-change');
        })
    },
    methods: {
        show() {
            this.getPosition();
            this.$utils.$page.open('/pages/city/city?event=x-city');
        },
        getPosition(){
            if(!map.isReady()){return ;}
            this.positionLoading=true;
            map.getCurrentPosition().then((result) => {
                this.getAddress([result.position.lng, result.position.lat]);
                this.$store.dispatch('setLocation', {
                    latitude: result.position.lat,
                    longitude: result.position.lng
                });
            }).catch(() => {
            }).finally(() => {
                this.positionLoading=false;
            });
        },
        getAddress(lnglat) {
            map.getAddress(lnglat).then(result=>{
                this.$store.dispatch('setCity', {
                    title: result.regeocode.addressComponent.city
                });
            }).catch(err=>{
                console.log(err);
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.city-title {
    min-width: 60px;
    max-width: 20vw;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>